package com.dxl.web.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dxl.common.utils.Utils;

/**
 * Servlet请求工具类
 * @author 邓小林
 */
public class RequestUtils {
    public static String getRoot(HttpServletRequest request) {
        int port = request.getServerPort();
        return "http://" + request.getServerName() + (port == 80 ? "" : ":" + String.valueOf(port)) + request.getContextPath();
    }
    
    public static String getCookieValue(HttpServletRequest req, String key) {
		Cookie[] cookies = req.getCookies();
		if (Utils.isNotEmpty(cookies)) {
			for (Cookie c : cookies) {
				if (c.getName().equals(key)) {
					return c.getValue();
				}
			}
		}
		return "";
	}
    
    public static void addCookie(HttpServletResponse resp, String key, String value) {
    	addCookie(resp, key, value, null, false, null, "/");
    }
    
    public static void addCookie(HttpServletResponse resp, String key, String value, Integer maxAge) {
    	addCookie(resp, key, value, maxAge, false, null, "/");
    }
	
	public static void addCookie(HttpServletResponse resp, String name, String value, Integer expireSecs, boolean secure, String domain, String path) {
		Cookie cookie = new Cookie(name, value);
		if (!Utils.isNull(expireSecs)) {
			cookie.setMaxAge(expireSecs);
		}
		cookie.setSecure(secure);
		cookie.setPath(path);
		if (!Utils.isBlank(domain)) {
			cookie.setDomain(domain);
		}
		
		resp.addCookie(cookie);
	}
	
	public static String getValueFromRequest(HttpServletRequest req, String key) {
		String value = getCookieValue(req, key);
		if (Utils.isBlank(value)) {
			value = req.getParameter(key);
		}
		return value;
	}
}
